// pages/course/course.js
const {
  getCourses,
  getCourseDetail,
  searchCourse
} = require('../../services/courseReq');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageNum: 1,
    pageSize: 10,
    searchPageNum: 1,
    courseList: [],
    searchList: [],
    // 是否加载完毕
    isFinish: false,
    isSearchFinish: false,
    // 搜索的值
    searchValue: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCourse()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.searchValue === '') {
      this.setData({
        pageNum: this.data.pageNum + 1
      })
      this.getCourse()
    } else {
      this.setData({
        searchPageNum: this.data.searchPageNum + 1
      })
      this.handleSearchCourse()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 获取全部课程
  getCourse() {
    if (this.data.isFinish) {
      return
    }
    wx.showLoading({
      title: '加载中',
    })
    getCourses(this.data.pageNum, this.data.pageSize, res => {
      let list = res.data.data.list
      if (list.length < this.data.pageSize) {
        this.setData({
          isFinish: true
        })
      }
      this.setData({
        courseList: this.data.courseList.concat(list)
      })
      wx.hideLoading()
    })
  },

  // 获取课程详情
  handleGetDetail(e) {
    const courseId = e.currentTarget.dataset.courseid
    wx.navigateTo({
      url: '../courseDetail/courseDetail?id=' + courseId,
    })
  },

  // 搜索更新
  handleSearchChange(e) {
    this.setData({
      searchValue: e.detail,
      searchList: [],
      searchPageNum: 1,
      isSearchFinish: false
    })
  },

  // 搜索课程
  handleSearchCourse() {
    if (this.data.isSearchFinish) {
      return
    }
    wx.showLoading({
      title: '搜索中',
    })
    searchCourse(this.data.searchValue, this.data.searchPageNum, this.data.pageSize, res => {
      let list = res.data.data.list
      if (list.length < this.data.pageSize) {
        this.setData({
          isSearchFinish: true
        })
      }
      this.setData({
        searchList: this.data.searchList.concat(list)
      })
      wx.hideLoading()
    })
  }
})